import { defineStore } from 'pinia';
import { fetchHistory, fetchRealtime } from '../services/api';
import type { SensorReading } from '../types';

export const useDataStore = defineStore('data', {
  state: () => ({
    latest: null as SensorReading | null,
    history: [] as SensorReading[],
    loading: false,
    polling: false,
    pollMs: 2000,
    error: '' as string | ''
  }),
  actions: {
    async loadHistory() {
      this.loading = true; this.error = '';
      try {
        const res = await fetchHistory();
        this.history = res.readings;
        if (this.history.length > 0) this.latest = this.history[this.history.length - 1];
      } catch (e: any) {
        this.error = e?.message || '加载历史失败';
      } finally {
        this.loading = false;
      }
    },
    async loadRealtime() {
      try {
        const res = await fetchRealtime();
        this.latest = res.reading;
        this.history.push(res.reading);
        if (this.history.length > 1000) this.history.shift();
      } catch (e: any) {
        this.error = e?.message || '加载实时数据失败';
      }
    },
    startPolling() {
      if (this.polling) return;
      this.polling = true;
      const run = async () => {
        if (!this.polling) return;
        await this.loadRealtime();
        setTimeout(run, this.pollMs);
      };
      run();
    },
    stopPolling() { this.polling = false; }
  }
});



